package com.yuyou.hxyy.service.api.voice;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

public class BaiduAipUtils {

    private static final Logger logger = LoggerFactory.getLogger(BaiduAipUtils.class);
    public static final String APP_ID = "11732075";
    public static final String API_KEY = "bLUZHgYhMdFuNDsp1hR3dSrN";
    public static final String SECRET_KEY = "vesI0udkuKmCpatYa5GK8KkcVLrrXf8F";


    public static byte[] getAudio(String word , Integer per, Integer spd, Integer pit, Integer vol){
        // 初始化一个AipSpeech
        AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
        /*client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理*/

        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
//        System.setProperty("aip.log4j.conf", "/resources/logback-boot.xml");

        HashMap<String, Object> options = new HashMap<>();
        options.put("spd",4);
        if(spd != null){
            options.put("spd" , spd);
        }
        if(pit != null){
            options.put("pit" , pit);
        }
        if(vol != null){
            options.put("vol" , vol);
        }
        options.put("per",per);//男声
        //options.put("aue", 6);//wav格式，不传默认为mp3格式
        // 调用接口
        TtsResponse res = client.synthesis(word, "zh", 1, options);
        byte[] data = res.getData();
        JSONObject res1 = res.getResult();
        if (data != null) {
            try {
                logger.info("success baidu "+"百度音频翻译：" + word +",接口调用成功");
//              Util.writeBytesToFileSystem(data, "/Users/yuan/output.mp3");
               return data;
            } catch (Exception e) {
                logger.info("error baidu "+"百度音频翻译：" + word +",接口调用失败：",e);
            }
        }else if(res1 != null){
            logger.info("error baidu "+"百度音频翻译：" + word +",接口调用失败：" + res1.toString());
        }
        return null;

    }


    /*public static void main(String[] args) throws IOException {
        byte[] data = BaiduAipUtils.getAudio("tomato" , 0);
        Util.writeBytesToFileSystem(data, "/Users/yuan/tomato.wav");
    }*/
}
